package com.lxq.LeetCode.bitwiseOperation;

public class bitwiseOperation {
    public static void main(String[] args) {
        System.out.println(add(3, 1));
        System.out.println(subtraction(2, 1));
    }

    //取符号
    public static int getSign(int n) {
        return n >> 31;
    }

    //求绝对值
    public static int positive(int n) {
        return (getSign(n) == 1) ? negtive(n) : n;
    }

    //取相反数
    public static int negtive(int n) {
        return add(~n, 1);
    }

    //加法
    public static int add(int a, int b) {
        return b != 0 ? add(a ^ b, (a & b) << 1) : a;
    }

    //减法
    public static int subtraction(int a, int b) {
        return add(a, negtive(b));
    }

    //乘法
    int multiply(int a, int b) {
        //如果两个数符号位不相容，则结果为负
        boolean isNegtive = (getSign(a) ^ getSign(b)) == 1;

        a = positive(a);
        b = positive(b);
        int res = 0;
        while (b==1) {
            //当b的对应位是1时，才需要加a
            if((b & 1)==1){
                res = add(res, a);
            }
            a = a << 1; //a左移
            b = b >> 1; //b右移
        }
        return isNegtive ? negtive(res) : res;
    }

    //除法


}
